<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>链表练习</title>
</head>
<body>
  <script>
    class Node {
      constructor(data) {
        this.data = data
        this.next = null
      }
    }
    class ListNode {
      constructor() {
        this.head = null
        this.length = 0
      }

      append(val) {
        if(this.length === 0) {
          this.head = new Node(val)
        }else{
          // 找到最后一个点，并添加
          let cur = this.head
          while(cur.next) {
            cur = cur.next
          }
          // 此时cur.next === null
          cur.next = new Node(val)
        }
        this.length += 1
      }
      // index 从0开始
      removeAt(index) {
        if(index > this.length) return
        let pre
        let cur = this.head
        let i = 0
        if(index === 0) {
          this.head = cur.next
        }else{
          while(i<index) {
            i++
            pre = cur
            cur = cur.next
          }
          pre.next = cur.next
          cur.next = null
        }
        this.length -= 1
      }

      print() {
        let arr = []
        let cur = this.head
        while(cur) {
          arr.push(cur.data)
          cur = cur.next
        }
        return arr.join('===>')
      }
    }
    let lists = new ListNode()
    lists.append('a')
    lists.append('b')
    lists.append('c')
    lists.append('d')
    console.log(lists.print());
  </script>
</body>
</html>